package com.sun.common.authoriza.util;

import com.sun.common.authoriza.provider.CurrentUser;
import com.sun.common.model.UserModel;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <pre>
 * Title :  当前用户信息工具类
 * </pre>
 *
 * @author : SunJiYong
 * @since : 2022-01-13
 **/
public class CurrentUserUtils {

	private CurrentUserUtils() {

	}

	public static Map<String, Object> getOAuth2AuthenticationDetailsInfo() {
		Map<String, Object> oauth2AuthenticationMap = new HashMap<>();
		OAuth2Authentication oauth2Authentication = (OAuth2Authentication) SecurityContextHolder.getContext().getAuthentication();
		UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) oauth2Authentication
				.getUserAuthentication();
		CurrentUser currentUser=(CurrentUser) usernamePasswordAuthenticationToken.getPrincipal();//(CurrentUser) principal.get("currentUser");
		oauth2AuthenticationMap.put("user",currentUser.getCurrentUser());
		Collection<GrantedAuthority> authorities = ((CurrentUser) usernamePasswordAuthenticationToken.getPrincipal()).getAuthorities();
		oauth2AuthenticationMap.put("authorities", AuthorityUtils.authorityListToSet(authorities));
		return oauth2AuthenticationMap;
	}

	//获取当前操作用户的用户名
	public static String  getOperateUserName(){
		Map<String, Object> currentUser =getOAuth2AuthenticationDetailsInfo();
		return ((UserModel) currentUser.get("user")).getAccount();
	}


}
